import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:schedule_self_client/api/schedule_self_server/task.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_api.dart';
import 'package:schedule_self_client/api/schedule_self_server/task_detail_resp.dart';
import 'package:schedule_self_client/common/simple_resp.dart';
import 'package:schedule_self_client/common/style_common.dart';
import 'package:schedule_self_client/ui/components/deadline_widget.dart';
import 'package:schedule_self_client/utils/time_util.dart';

class TaskDetailPage extends StatefulWidget {
  final int taskId;

  const TaskDetailPage({super.key, required this.taskId});

  @override
  State<TaskDetailPage> createState() => _TaskDetailPageState();
}

class _TaskDetailPageState extends State<TaskDetailPage> {
  Task? _task;
  final _descriptionEditingController = TextEditingController();
  final _taskNameEditingController = TextEditingController();
  DateTime? _deadline;

  @override
  void initState() {
    super.initState();
    _loadTask(widget.taskId);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('工作'),
        actions: [
          if (_task != null)
            IconButton(
                onPressed: () async {
                  var taskMap = _task!.toJson();
                  taskMap.update(
                      'name', (_) => _taskNameEditingController.text);
                  taskMap.update(
                      'description', (_) => _descriptionEditingController.text);
                  if (taskMap.containsKey('deadline')) {
                    taskMap.update('deadline',
                        (_) => TimeUtil.formatTimeToBackend(_deadline!));
                  } else {
                    taskMap.putIfAbsent('deadline',
                        () => TimeUtil.formatTimeToBackend(_deadline!));
                  }
                  await TaskApi.updateTask(Task.fromJson(taskMap));
                  BotToast.showText(text: '保存成功');
                },
                icon: const Icon(Icons.save)),
        ],
      ),
      body: Center(
        child: _task == null
            ? const CircularProgressIndicator()
            : Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        IconButton(
                            onPressed: () {
                              _taskCompleteFlagChange(_task!);
                            },
                            icon: _task!.isComplete()
                                ? const Icon(Icons.check_circle_outline)
                                : Icon(
                                    Icons.circle_outlined,
                                    size:
                                        StyleCommon.getTitleLargeSize(context),
                                  )),
                        Expanded(
                            child: TextField(
                          controller: _taskNameEditingController,
                          style: Theme.of(context).textTheme.titleLarge,
                          decoration: const InputDecoration(
                            border: InputBorder.none,
                          ),
                        )),
                        IconButton(
                            onPressed: () {},
                            icon: Icon(
                              Icons.star_border,
                              size: StyleCommon.getTitleLargeSize(context),
                            ))
                      ],
                    ),
                    const SizedBox(height: 16),
                    TextField(
                      controller: _descriptionEditingController,
                      decoration: const InputDecoration(
                        border: InputBorder.none,
                      ),
                    ),
                    const SizedBox(height: 16),
                    DeadlineWidget(
                      dateSelectCallback: (newDeadline) {
                        if (newDeadline != null) {
                          setState(() {
                            _deadline = newDeadline;
                          });
                        }
                      },
                      deadline: _deadline,
                    )
                  ],
                ),
              ),
      ),
    );
  }

  Future<void> _loadTask(int taskId) async {
    TaskDetailResp resp = await TaskApi.getTaskDetail(taskId);
    setState(() {
      _task = resp.data;
      _descriptionEditingController.text = _task!.getDescriptionWithDefault();
      _taskNameEditingController.text = _task!.name;
      if (_task!.deadline != null) {
        _deadline = DateTime.parse(_task!.deadline!);
      }
    });
  }

  _taskCompleteFlagChange(Task task) async {
    SimpleResp simpleResp = await TaskApi.taskCompleteFlagChange(task.id);
    if (simpleResp.success) {
      setState(() {
        _loadTask(task.id);
      });
    }
  }

  String _showCompleteTime(String completeTimeStr) {
    DateTime completeTime = DateTime.parse(completeTimeStr);
    DateFormat dateFormat =
        DateFormat('M月d日 E', Localizations.localeOf(context).languageCode);
    return dateFormat.format(completeTime);
  }
}
